import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { customerApi } from '@/api/customer'
import type { Customer } from '@/types/customer'
import { formatDateTime } from '@/utils/format'

// 查询表单
const queryForm = reactive({
  page: 1,
  limit: 10,
  keywords: '',
  type: '',
  discardTimeRange: [],
})

// 客户列表
const customerList = ref<Customer[]>([])
const total = ref<number>(0)
const loading = ref<boolean>(false)

// 选中的客户
const selectedCustomers = ref<Customer[]>([])

// 详情抽屉
const detailDrawerVisible = ref<boolean>(false)
const currentCustomer = ref<Customer>({} as Customer)

// 表单引用
const queryFormRef = ref<any>(null)

// 处理查询
const handleSearch = async () => {
  loading.value = true
  try {
    const params: any = {
      page: queryForm.page,
      limit: queryForm.limit,
      is_discard: 1, // 只查询废弃的客户
    }

    if (queryForm.keywords) {
      params.keywords = queryForm.keywords
    }

    if (queryForm.type) {
      params.customer_type = queryForm.type
    }

    if (queryForm.discardTimeRange && queryForm.discardTimeRange.length === 2) {
      params.start_discard_time = queryForm.discardTimeRange[0]
      params.end_discard_time = queryForm.discardTimeRange[1]
    }

    const response = await customerApi.getDiscardCustomerList(params)
    if (response && response.code === 0) {
      // 修复：正确处理分页数据结构
      customerList.value = response.data?.list || []
      total.value = response.data?.total || 0
    } else {
      customerList.value = []
      total.value = 0
      ElMessage.error(response?.msg || '获取废弃客户列表失败')
    }
  } catch (error) {
    customerList.value = []
    total.value = 0
    console.error('获取废弃客户列表失败:', error)
    ElMessage.error('获取废弃客户列表失败')
  } finally {
    loading.value = false
  }
}

// 重置查询
const handleReset = () => {
  queryForm.keywords = ''
  queryForm.type = ''
  queryForm.discardTimeRange = []
  queryForm.page = 1
  handleSearch()
}

// 恢复客户
const handleRestore = (row: Customer) => {
  ElMessageBox.confirm(`确定要恢复客户"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        // 使用discardCustomer接口传入is_discard=0来恢复客户
        const response = await customerApi.discardCustomer({ id: row.id, is_discard: 0 })
        if (response && (response as any).data.code === 0) {
          ElMessage.success('恢复成功')
          handleSearch()
        } else {
          ElMessage.error((response as any)?.msg || '恢复失败')
        }
      } catch (error) {
        console.error('恢复客户失败:', error)
        ElMessage.error('恢复失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消恢复')
    })
}

// 删除客户（彻底删除）
const handleDelete = (row: Customer) => {
  ElMessageBox.confirm(`确定要彻底删除客户"${row.name}"吗？此操作不可恢复！`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error',
  })
    .then(async () => {
      try {
        const response = await customerApi.deleteCustomerDetail({ id: row.id })
        if (response && (response as any).data.code === 0) {
          ElMessage.success('删除成功')
          handleSearch()
        } else {
          ElMessage.error((response as any)?.msg || '删除失败')
        }
      } catch (error) {
        console.error('删除客户失败:', error)
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 批量恢复客户
const handleBatchRestore = () => {
  if (selectedCustomers.value.length === 0) {
    ElMessage.warning('请先选择要恢复的客户')
    return
  }

  ElMessageBox.confirm(`确定要恢复选中的${selectedCustomers.value.length}个客户吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const ids = selectedCustomers.value.map(item => item.id)
        // 批量恢复客户
        const restorePromises = ids.map(id => customerApi.discardCustomer({ id, is_discard: 0 }))
        const results = await Promise.all(restorePromises)

        // 检查所有恢复操作是否都成功
        const allSuccess = results.every(result => result && (result as any).code === 0)

        if (allSuccess) {
          ElMessage.success('批量恢复成功')
          handleSearch()
        } else {
          ElMessage.error('部分恢复失败')
          handleSearch()
        }
      } catch (error) {
        console.error('批量恢复客户失败:', error)
        ElMessage.error('批量恢复失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消恢复')
    })
}

// 处理选择变化
const handleSelectionChange = (selection: Customer[]) => {
  selectedCustomers.value = selection
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  queryForm.limit = val
  queryForm.page = 1
  handleSearch()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  queryForm.page = val
  handleSearch()
}

// 关闭详情抽屉
const closeDetailDrawer = () => {
  detailDrawerVisible.value = false
}

// 导出所有需要在模板中使用的变量和方法
export {
  // 响应式数据
  queryForm,
  customerList,
  total,
  loading,
  selectedCustomers,
  detailDrawerVisible,
  currentCustomer,
  queryFormRef,

  // 方法
  handleSearch,
  handleReset,
  handleRestore,
  handleDelete,
  handleBatchRestore,
  handleSelectionChange,
  handleSizeChange,
  handleCurrentChange,
  closeDetailDrawer,
  formatDateTime,
}
